
// 正则表达式定义
const telReg =/\{\{.+?\}\}/g; //匹配 {{xx}} 整个内容
const contentReg = /(?<=(\{\{)).+?(?=(\}\}))/g // 匹配{{}}里面的xx

// 替换template的内容



/**
 * @params
 *   name @string   'Search'
 *   data @Record<any, any>   {}
 *   methods @Record<any, any>   {} 
 *   el @srting 选择器 '#root'   
 * @说明 - 使用例子
 *   new Component({
 *      data: {
 *          count: 0,
 *      },
 *      methods: {
 *           
 *      }
 *   });
 */
function Component(params = {}){
    const { name, data = {}, methods = {}, el } = params;
    // 根据name得出对应的模板UI和挂载的dom实例
    this.tpl = document.querySelector(`template[name=${name}]`);
    this.el = document.querySelector(el);
    // 外面包一个div
    this.wrap = document.createElement('div');
    // 把参数配置到实例属性上
    this.data = data;
    // 把methods的this进行绑定
    this.methods = {};
    for(let i in methods){
        this.methods[i] = methods[i].bind(this)
    }

    // 给模板打入数据，获取UI内容
    this.getUI = () => {
        return this.tpl.innerHTML.replace(telReg, (item)=>{
            const key = item.match(contentReg)[0];
            return this.data[key];
        })
    }
    // 渲染出来，挂载到el上
    this.render = () => {
        console.log('render')
        const UI = this.getUI();
        this.wrap.innerHTML = UI; 
    }
    // VM绑定器
    const config = {};
    for(let i in this.data){
        let proxyValue = this.data[i];
        config[i] = {
            get: () => proxyValue,
            set: (value)=>{
                console.log('proxy')
                proxyValue = value;
                this.render(); 
            }
        } 
    }
    Object.defineProperties(data,config);
    // 初始化第一次render和挂载
    this.render();
    this.el.appendChild(this.wrap)
}